import time
import pymysql
from selenium import webdriver
from selenium.webdriver.common.by import By

driver = webdriver.Edge()
driver.get("https://www.jd.com/")
driver.find_element(By.CSS_SELECTOR, "#key").send_keys("电脑笔记本")
driver.find_element(By.CSS_SELECTOR, "#search > div > div.form > button > i").click()
time.sleep(2)
weilist=[]

for i in range(5):
    mylist = driver.find_elements(By.CSS_SELECTOR, "li")
    for li in mylist:
        try:
            llist = [
                li.find_element(By.CSS_SELECTOR, ".p-name em").text.replace("\n", " "),
                li.find_element(By.CSS_SELECTOR, ".p-name a").get_attribute("title").replace("\n", " ").replace("-"," ").replace("'","‘"),
                li.find_element(By.CSS_SELECTOR, ".p-price strong").text,
                li.find_element(By.CSS_SELECTOR, ".p-commit strong").text,
                li.find_element(By.CSS_SELECTOR, ".J_im_icon a").text,
                li.find_element(By.CSS_SELECTOR, ".p-icons").text.replace("\n", "，")
            ]
            weilist.append(llist)
        except:
            pass
    driver.find_element(By.CSS_SELECTOR, "#J_bottomPage > span.p-num > a.pn-next > i").click()
    time.sleep(2)

for jun in weilist:
    connect=pymysql.connect(host="localhost",user="root",password="123456",db="spiderwork")
    course=connect.cursor()
    sql="INSERT INTO 京东电脑笔记本 values ('%s','%s','%s','%s','%s','%s')"%(jun[0],jun[1],jun[2],jun[3],jun[4],jun[5])
    try:
        print("正在写入数据！")
        course.execute(sql)
        connect.commit()
    except Exception as e:
        print("数据写入失败！",e)
        connect.rollback()
        connect.close()
